package com.xu.sso.core.utils;

import com.xu.sso.core.config.SystemConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.text.MessageFormat;

@Slf4j
@Component
public class MailUtil {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private SystemConfig config;

    public void send(String toAddress, String title, String user, String pwd) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
            helper.setFrom(config.getMailFrom());
            helper.setTo(toAddress);
            helper.setSubject(title);
            String content = MessageFormat.format(mailBodyTemplate, title, user, pwd);
            helper.setText(content, true);
            javaMailSender.send(message);
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>>MailUtil.send error===={}", e);
        }
    }

    private static final String mailBodyTemplate =
            "<table border=\"1\" bordercolor=\"#4a4aff\" style=\"border-collapse:collapse;text-align: center;\">\n" +
                    "   <thead style=\"font-weight: bold;background-color: #c4e1ff;\">" +
                    "      <tr>\n" +
                    "         <td width=\"50%\" >用户名</td>\n" +
                    "         <td width=\"50%\" >密码</td>\n" +
                    "      </tr>\n" +
                    "   <thead/>\n" +
                    "   <tbody>\n" +
                    "      <tr>\n" +
                    "         <td>{1}</td>\n" +
                    "         <td>{2}</td>\n" +
                    "      </tr>\n" +
                    "   <tbody>\n" +
                    "</table>";

}
